package com.rbac.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.modules.system.dto.UserDTO;
import com.rbac.modules.system.dto.UserQuery;
import com.rbac.modules.system.entity.SysUser;
import com.rbac.modules.system.mapper.SysUserMapper;
import com.rbac.modules.system.service.SysPermissionService;
import com.rbac.modules.system.service.SysRoleService;
import com.rbac.modules.system.service.SysUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysRoleService roleService;

    @Resource
    private SysPermissionService permissionService;

    @Override
    public Page<SysUser> page(UserQuery query) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(SysUser::getId, SysUser::getUsername, SysUser::getRealName,
                      SysUser::getPhone, SysUser::getEmail, SysUser::getAvatar,
                      SysUser::getStatus, SysUser::getCreateTime, SysUser::getUpdateTime)
                .like(StringUtils.hasText(query.getUsername()), SysUser::getUsername, query.getUsername())
                .like(StringUtils.hasText(query.getRealName()), SysUser::getRealName, query.getRealName())
                .like(StringUtils.hasText(query.getPhone()), SysUser::getPhone, query.getPhone())
                .like(StringUtils.hasText(query.getEmail()), SysUser::getEmail, query.getEmail())
                .eq(query.getStatus() != null, SysUser::getStatus, query.getStatus())
                .orderByDesc(SysUser::getCreateTime);

        return this.page(new Page<>(query.getCurrent(), query.getSize()), wrapper);
    }

    @Override
    public void create(UserDTO userDTO) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userDTO, user);
        user.setCreateTime(LocalDateTime.now());
        // 设置默认密码为123456
        user.setPassword(md5("123456"));
        this.save(user);
    }

    @Override
    public void update(UserDTO userDTO) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(userDTO, user);
        // TODO: 密码加密
        this.updateById(user);
    }

    @Override
    public void delete(Long[] ids) {
        this.removeByIds(Arrays.asList(ids));
    }

    @Override
    public void resetPassword(Long[] ids) {
        // TODO: 实现密码重置逻辑
        for (Long id : ids) {
            SysUser user = new SysUser();
            user.setId(id);
            user.setPassword("123456"); // 默认密码
            // TODO: 密码加密
            this.updateById(user);
        }
    }

    @Override
    public List<String> getUserPermissions(Long userId) {
        return permissionService.getPermissionCodesByUserId(userId);
    }

    @Override
    public List<String> getUserRoles(Long userId) {
        return roleService.getRoleCodesByUserId(userId);
    }

    /**
     * MD5加密
     */
    private String md5(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(password.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            log.error("MD5加密失败", e);
            return password;
        }
    }
}
